<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import ChatInterface from '../components/ChatInterface.vue'
import FloatingEmojis from '../components/FloatingEmojis.vue'
import ChatRoomHistory from '../components/ChatRoomHistory.vue'
import { connectToManusSSE, stopChat } from '../services/api'

const chatInterface = ref(null)
const chatId = ref('')
const currentAiMessageId = ref(null)
const isGenerating = ref(false)
const isHistoryFlipped = ref(false)
const showEmoji = ref(false)

// 表情数组
const emojis = ['🕒', '📜', '💫', '✨', '🌟', '💭']
const currentEmoji = ref(emojis[0])

// 定时显示表情
let emojiTimer = null

const showEmojiAnimation = () => {
  // 随机选择一个表情
  currentEmoji.value = emojis[Math.floor(Math.random() * emojis.length)]
  showEmoji.value = true
  
  // 1秒后隐藏表情
  setTimeout(() => {
    showEmoji.value = false
  }, 1000)
}

onMounted(() => {
  // 每4秒显示一次表情
  emojiTimer = setInterval(showEmojiAnimation, 4000)
})

onUnmounted(() => {
  if (emojiTimer) {
    clearInterval(emojiTimer)
  }
})

// 生成随机房间ID
const generateRoomId = () => {
  return 'super_' + Math.random().toString(36).substring(2, 15)
}

// 初始化房间ID
const initRoomId = () => {
  const savedId = localStorage.getItem('deviceRoomId_super')
  if (savedId) {
    chatId.value = savedId
  } else {
    chatId.value = generateRoomId()
    localStorage.setItem('deviceRoomId_super', chatId.value)
  }
}

const updateChatId = (newId) => {
  chatId.value = newId
  localStorage.setItem('deviceRoomId_super', newId)
  // 清空当前聊天记录
  chatInterface.value.chatMessages = []
  // 添加新的欢迎消息
  setTimeout(() => {
    const welcomeId = addNewAiMessage()
    chatInterface.value.addAiMessage('你好！我是AI超级智能体，我可以回答各种问题并提供帮助。请问有什么我可以帮你的吗？', welcomeId)
    chatInterface.value.completeAiMessage(welcomeId)
  }, 500)
}

// 添加新的AI消息并返回消息ID
const addNewAiMessage = () => {
  const messageId = Date.now()
  // 创建新的AI消息
  chatInterface.value.chatMessages.push({
    id: messageId,
    text: '',
    isUser: false,
    timestamp: new Date().toLocaleTimeString(),
    completed: false
  })
  return messageId
}

// 发送消息到后端
const sendMessage = (message) => {
  isGenerating.value = true
  // 连接到SSE
  connectToManusSSE(
    chatId.value,
    message,
    // 消息回调 - 处理流式响应
    (data) => {
      // 如果是新消息，创建新的AI消息气泡
      if (!currentAiMessageId.value) {
        currentAiMessageId.value = addNewAiMessage()
      }
      
      // 添加流式响应内容，并在每次响应后添加额外的换行
      chatInterface.value.addAiMessage(data + '\n', currentAiMessageId.value)
    },
    // 完成回调
    () => {
      chatInterface.value.completeAiMessage(currentAiMessageId.value)
      currentAiMessageId.value = null
      isGenerating.value = false
    }
  )
}

// 停止生成回答
const stopGeneration = async () => {
  await stopChat(chatId.value)
  if (currentAiMessageId.value) {
    chatInterface.value.completeAiMessage(currentAiMessageId.value)
    currentAiMessageId.value = null
  }
  isGenerating.value = false
}

// 处理历史记录点击
const handleHistoryClick = () => {
  isHistoryFlipped.value = true
  setTimeout(() => {
    // TODO: 这里添加获取历史记录的逻辑
    isHistoryFlipped.value = false
  }, 600)
}

onMounted(() => {
  initRoomId()
  // 添加欢迎消息
  setTimeout(() => {
    const welcomeId = addNewAiMessage()
    chatInterface.value.addAiMessage('你好！我是AI超级智能体，我可以回答各种问题并提供帮助。请问有什么我可以帮你的吗？', welcomeId)
    chatInterface.value.completeAiMessage(welcomeId)
  }, 500)
})
</script>

<template>
  <div class="chat-container">
    <FloatingEmojis />
    <ChatRoomHistory
      :currentRoomId="chatId"
      @select-room="updateChatId"
      type="super"
    />
    <ChatInterface
      ref="chatInterface"
      title="AI 超级智能体"
      :chatId="chatId"
      userAvatar="👤"
      aiAvatar="🤖"
      @send-message="sendMessage"
      @update-chat-id="updateChatId"
      :isGenerating="isGenerating"
      :onStop="stopGeneration"
    />
    

  </div>
</template>

<style scoped>
.chat-container {
  position: relative;
  height: 100%;
  overflow: hidden;
  background-color: var(--bg-color);
}

/* 历史记录按钮样式 */
.history-button {
  position: fixed;
  top: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(30, 30, 40, 0.9);
  border: 1px solid rgba(0, 243, 255, 0.2);
  border-radius: 20px;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 100;
}

.history-button:hover {
  background: rgba(40, 40, 50, 0.95);
  border-color: var(--neon-blue);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 243, 255, 0.2);
}

.history-icon {
  width: 20px;
  height: 20px;
  color: var(--neon-blue);
  transition: transform 0.3s ease;
}

.history-button:hover .history-icon {
  transform: rotate(15deg);
}

/* 表情弹出动画 */
.emoji-popup {
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translateX(-50%) translateY(10px);
  font-size: 24px;
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  pointer-events: none;
}

.emoji-popup.show {
  opacity: 1;
  transform: translateX(-50%) translateY(0);
}

@media (max-width: 768px) {
  .history-button {
    padding: 6px 12px;
    font-size: 14px;
  }
  
  .history-icon {
    width: 16px;
    height: 16px;
  }
  
  .emoji-popup {
    font-size: 20px;
  }
}
</style>